import React from 'react';
import {injectIntl, language} from './intl';
import PropTypes from 'prop-types';
import {Button, Form, Row, Col, Switch, Card, Spin, Table, message} from 'antd';
import routes from './routes';
import {FORM_OPTIONS, PAGE, TABLE, FIXED_COLUMN_WIDTH, FORM_ROW_OPTIONS} from '../constants';
import {PERMISSION} from './constants';
import styles from './style.css';
import {formatAmount, conventEnumValueToString, formatPercent} from '../utils';
import Return from '../common/Return';
import TextInput from 'Shared/components/TextInput';
import {currency} from '../Enum';
import Ellipsis from 'ant-design-pro/lib/Ellipsis';
import {uniqBy, intersectionWith, isEqual} from 'lodash';
const FormItem = Form.Item;
const EMPTY_ARRAY = [];
const showDeletedLayout = {
    labelCol: {
        span: 16
    },
    wrapperCol: {
        span: 8
    }
};
const autosize = {min: 1};
export class Add extends React.PureComponent {
    state = {
        loading: false,
        hasOperat: false,
        isValidate: false,
        showDeleted: false,
        selectedRowKeys: [],
        isRepeat: false
    };

    componentDidMount() {
        this.props.init();
        this.ismounted = true;
    }

    componentWillUnmount() {
        this.ismounted = false;
        this.props.onUmount();
    }

    handleFilterChange = (value, name) => {
        if(!this.state.hasOperat)
            this.setState({
                hasOperat: true
            });
        this.props.onConditionsChange(name, value);
    };

    rowClassName = record => record.isDelete ? styles.color : ''
    
    onToggleShowDeleted= checked => {
        this.setState({
            showDeleted: checked
        });
    }

    onClickUpdateDetail = e => {
        const {id} = e.target.dataset;
        const {details = []} = this.props.conditions;
        const newDetails = details.map(v => {
            if(v.claimIdBak === id)
                return Object.assign({}, v, {
                    isDelete: !v.isDelete
                });
            return v;
        });
        this.props.onUpdateDetail(newDetails);
    };

    onSubmit = () => {
        const {details = []} = this.props.conditions;
        const data = details.filter(item => !item.isDelete);
        if(!data.length)
            return message.warn(this.props.intl.formatMessage({
                id: 'update.details.validate',
                defaultMessage: '清单不能为空'
            }));
        this.setState({
            loading: true
        });
        return this.props.onSubmit().then(success => {
            if(this.ismounted && !success)
                this.setState({
                    loading: false
                });
        });
    };
    
    onClickRepeatBtn = () => {
        const {details = []} = this.props.conditions;
        const repeats = uniqBy(details, 'repeatId');
        const result = [];
        for(let i = 0; i < details.length; i++) {
            const obj = details[i];
            let isExist = false;
            for(let j = 0; j < repeats.length; j++) {
                const aj = repeats[j];
                if(isEqual(obj, aj)) {
                    isExist = true;
                    break;
                }
            }
            if(!isExist)
                result.push(obj);
        }
        this.setState({
            isRepeat: true,
            details: details.filter(v => result.some(o => o.vin === v.vin && o.causePartCode === v.causePartCode && o.totalFee === v.totalFee))
        });
    }
    onClickReductionBtn = () => {
        this.setState({
            isRepeat: false
        });
    }
    render() {
        const languageIntl = language;
        const {details = []} = this.props.conditions;
        const dataSource = details.filter(item => this.state.showDeleted || !item.isDelete);
        const newdetails = this.state.isRepeat ? this.state.details : dataSource;
        const columns = [
            {
                title: this.props.intl.formatMessage({
                    id: 'update.column.code',
                    defaultMessage: '单据编号'
                }),
                dataIndex: 'code',
                width: 200,
            },
            {
                title: this.props.intl.formatMessage({
                    id: 'update.column.vin',
                    defaultMessage: 'VIN'
                }),
                dataIndex: 'vin',
                width: 160,
            },
            {
                title: this.props.intl.formatMessage({
                    id: 'update.column.productCategoryCode',
                    defaultMessage: '车型'
                }),
                dataIndex: 'productCategoryCode',
                width: 150,
                render: text => <span title={text}><Ellipsis length={20}>{text}</Ellipsis></span>
            },
            {
                title: this.props.intl.formatMessage({
                    id: 'update.column.partCode',
                    defaultMessage: '备件编号'
                }),
                dataIndex: 'partCode',
                width: languageIntl === 'pt-PT' ? 260 : 195,
                render: text => <span title={text}><Ellipsis length={20}>{text}</Ellipsis></span>
            },
            {
                title: this.props.intl.formatMessage({
                    id: 'update.column.partName',
                    defaultMessage: '备件名称'
                }),
                dataIndex: 'partName',
                width: 280,
                render: text => <span title={text}><Ellipsis length={28}>{text}</Ellipsis></span>
            },
            {
                title: this.props.intl.formatMessage({
                    id: 'update.column.isCaused',
                    defaultMessage: '是否主损件'
                }),
                dataIndex: 'isCaused',
                width: 280,
                render: text => text ? 'Y' : 'N'
            },
            {
                title: this.props.intl.formatMessage({
                    id: 'update.column.quantity',
                    defaultMessage: '备件数量'
                }),
                dataIndex: 'quantity',
                className: styles.textAlign,
                width: 150,
                render: text => formatAmount(text)
            },
            {
                title: this.props.intl.formatMessage({
                    id: 'update.column.currency',
                    defaultMessage: ' 币种'
                }),
                dataIndex: 'currency',
                width: 120,
                render: text => conventEnumValueToString(currency, text)
            }
        ];
        if(!this.props.isMoneyVisible)
            columns.splice(7, 0,
                {
                    title: this.props.intl.formatMessage({
                        id: 'update.column.price',
                        defaultMessage: '单价'
                    }),
                    dataIndex: 'price',
                    className: styles.textAlign,
                    width: 150,
                    render: text => formatAmount(text)
                },
                {
                    title: this.props.intl.formatMessage({
                        id: 'update.column.materialFee',
                        defaultMessage: '材料费'
                    }),
                    dataIndex: 'materialFee',
                    className: styles.textAlign,
                    width: 150,
                    render: text => formatAmount(text)
                },
                {
                    title: this.props.intl.formatMessage({
                        id: 'update.column.mgmtFee',
                        defaultMessage: '管理费'
                    }),
                    dataIndex: 'mgmtFee',
                    className: styles.textAlign,
                    width: 150,
                    render: text => formatAmount(text)
                },
                {
                    title: this.props.intl.formatMessage({
                        id: 'update.column.laborFee',
                        defaultMessage: '工时费'
                    }),
                    dataIndex: 'laborFee',
                    className: styles.textAlign,
                    width: languageIntl === 'pt-PT' ? 190 : 120,
                    render: text => formatAmount(text)
                },
                {
                    title: this.props.intl.formatMessage({
                        id: 'update.column.accessoryFee',
                        defaultMessage: '辅料费'
                    }),
                    dataIndex: 'accessoryFee',
                    className: styles.textAlign,
                    width: languageIntl === 'pt-PT' ? 180 : 120,
                    render: text => formatAmount(text)
                },
                {
                    title: this.props.intl.formatMessage({
                        id: 'update.column.totalFee',
                        defaultMessage: '费用合计'
                    }),
                    dataIndex: 'totalFee',
                    sorter: true,
                    className: styles.textAlign,
                    width: 120,
                    render: text => formatAmount(text)
                });
        if(!this.props.isDealerUser && !this.props.isMoneyVisible) {
            columns.splice(9, 0,
                {
                    title: this.props.intl.formatMessage({
                        id: 'update.column.mgmtFeeRate',
                        defaultMessage: '管理费率'
                    }),
                    dataIndex: 'mgmtFeeRate',
                    className: styles.textAlign,
                    width: 150,
                    render: text => formatPercent(text)
                });
            columns.splice(11, 0,
                {
                    title: this.props.intl.formatMessage({
                        id: 'update.column.laborPrice',
                        defaultMessage: '工时单价'
                    }),
                    dataIndex: 'laborPrice',
                    className: styles.textAlign,
                    width: languageIntl === 'pt-PT' ? 190 : 120,
                    render: text => formatAmount(text)
                });
        }
        if(!this.state.isRepeat)
            columns.push({
                title: this.props.intl.formatMessage({
                    id: 'tablePanel.column.action',
                    defaultMessage: '操作'
                }),
                dataIndex: 'claimId',
                width: 100,
                fixed: 'right',
                render: (text, record) => ({
                    children: <a onClick={this.onClickUpdateDetail} data-id={record.claimId}>
                        {this.state.showDeleted && record.isDelete
                            ? this.props.intl.formatMessage({
                                id: 'add.rollback',
                                defaultMessage: '恢复'
                            })
                            : this.props.intl.formatMessage({
                                id: 'add.delete',
                                defaultMessage: '删除'
                            })}
                    </a>,
                    props: {
                        rowSpan: text ? record.rowSpan : 0,
                    },
                })
                // render: (text, record) => (
                //     <a onClick={this.onClickUpdateDetail} data-id={record.id}>
                //         {this.state.showDeleted && record.isDelete
                //             ? this.props.intl.formatMessage({
                //                 id: 'add.rollback',
                //                 defaultMessage: '恢复'
                //             })
                //             : this.props.intl.formatMessage({
                //                 id: 'add.delete',
                //                 defaultMessage: '删除'
                //             })}
                //     </a>
                // )
            });
        let materialFee = 0;
        let mgmtFee = 0;
        let laborFee = 0;
        let suppleMaterialFee = 0;
        let outFee = 0;
        let totalFee = 0;
        details.filter(item => !item.isDelete).forEach(v => {
            materialFee += v.materialFee;
            mgmtFee += v.mgmtFee;
            laborFee += v.laborFee;
            suppleMaterialFee += v.accessoryFee;
            outFee += v.outFee;
            totalFee += v.totalFee;
        });
        const rowSelection = {
            selectedRowKeys: this.state.selectedRowKeys,
            onChange: selectedRowKeys => {
                this.setState({
                    selectedRowKeys
                });
            }
        };
        return (
            <div className={styles.detail}>
                <Spin spinning={this.props.loading || this.state.loading}>
                    <Form className="form-standard">
                        <Card title={this.props.intl.formatMessage({
                            id: 'update.order.title',
                            defaultMessage: '结算单信息'
                        })}>
                            <Row>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem {...FORM_OPTIONS.item}
                                        label={this.props.intl.formatMessage({
                                            id: 'update.info.code',
                                            defaultMessage: '结算单号'
                                        })}>
                                        {this.props.conditions.code}
                                    </FormItem>
                                </Col>
                                {this.props.isDealerUser ? null
                                    : <Col {...FORM_OPTIONS.col}>
                                        <FormItem {...FORM_OPTIONS.item}
                                            label={this.props.intl.formatMessage({
                                                id: 'update.info.dealerCode',
                                                defaultMessage: '总代'
                                            })}>
                                            {this.props.conditions.dealerCode}
                                        </FormItem>
                                    </Col>}
                                {!this.props.isMoneyVisible &&
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem {...FORM_OPTIONS.item}
                                        label={this.props.intl.formatMessage({
                                            id: 'update.info.materialFee',
                                            defaultMessage: '材料费'
                                        })}>
                                        {formatAmount(materialFee)}
                                    </FormItem>
                                </Col>}
                                {!this.props.isMoneyVisible &&
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem {...FORM_OPTIONS.item}
                                        label={this.props.intl.formatMessage({
                                            id: 'update.info.mgmtFee',
                                            defaultMessage: '配件管理费'
                                        })}>
                                        {formatAmount(mgmtFee)}
                                    </FormItem>
                                </Col>}
                                {!this.props.isMoneyVisible &&
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem {...FORM_OPTIONS.item}
                                        label={this.props.intl.formatMessage({
                                            id: 'update.info.laborFee',
                                            defaultMessage: '工时费'
                                        })}>
                                        {formatAmount(laborFee)}
                                    </FormItem>
                                </Col>}
                                {!this.props.isMoneyVisible &&
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem {...FORM_OPTIONS.item}
                                        label={this.props.intl.formatMessage({
                                            id: 'update.info.suppleMaterialFee',
                                            defaultMessage: '辅料费'
                                        })}>
                                        {formatAmount(suppleMaterialFee)}
                                    </FormItem>
                                </Col>}
                                {/* <Col {...FORM_OPTIONS.col}>
                                    <FormItem {...FORM_OPTIONS.item}
                                        label={this.props.intl.formatMessage({
                                            id: 'update.info.outFee',
                                            defaultMessage: '外出费用'
                                        })}>
                                        {formatAmount(outFee)}
                                    </FormItem>
                                </Col> */}
                                {!this.props.isMoneyVisible &&
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem {...FORM_OPTIONS.item}
                                        label={this.props.intl.formatMessage({
                                            id: 'update.info.totalFee',
                                            defaultMessage: '费用合计'
                                        })}>
                                        {formatAmount(totalFee)}
                                    </FormItem>
                                </Col>}
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem {...FORM_OPTIONS.item}
                                        label={this.props.intl.formatMessage({
                                            id: 'update.info.currency',
                                            defaultMessage: '币种'
                                        })}>
                                        {conventEnumValueToString(currency, this.props.conditions.currency)}
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem className={styles.multiLabel} {...FORM_OPTIONS.item}
                                        label={this.props.intl.formatMessage({
                                            id: 'update.info.department',
                                            defaultMessage: '报销部门'
                                        })}>
                                        <TextInput name="department" value={this.props.conditions.department} onBlur={this.handleFilterChange} />
                                    </FormItem>
                                </Col>
                            </Row>
                            <Row>
                                <FormItem {...FORM_ROW_OPTIONS.item} label={this.props.intl.formatMessage({
                                    id: 'update.info.remark',
                                    defaultMessage: '备注'
                                })}>
                                    <TextInput type="textarea" autosize={autosize} name="remark" value={this.props.conditions.remark} onBlur={this.handleFilterChange} />
                                </FormItem>
                            </Row>
                        </Card>
                        <Card
                            extra={!this.state.isRepeat && <FormItem
                                {...showDeletedLayout}
                                label={this.props.intl.formatMessage({
                                    id: 'update.claimWorkItemDetail.showDeleted',
                                    defaultMessage: '显示删除项'
                                })}>
                                <Switch
                                    size="small"
                                    onClick={this.onToggleShowDeleted}
                                    checked={this.state.showDeleted}
                                    checkedChildren={this.props.intl.formatMessage({
                                        id: 'yes',
                                        defaultMessage: '是'
                                    })}
                                    unCheckedChildren={this.props.intl.formatMessage({
                                        id: 'no',
                                        defaultMessage: '否'
                                    })} />
                            </FormItem>}
                            title={<Row><Col>{this.props.intl.formatMessage({
                                id: 'detail.details.title',
                                defaultMessage: '清单列表'
                            })}{' '}
                            {this.state.isRepeat ? <Button
                                className={styles.selectRepeatBtn}
                                size="small"
                                onClick={this.onClickReductionBtn}>
                                {this.props.intl.formatMessage({
                                    id: 'newPanel.operation.reduction',
                                    defaultMessage: '还原'
                                })}
                            </Button> : <Button
                                className={styles.selectRepeatBtn}
                                size="small"
                                onClick={this.onClickRepeatBtn}>
                                {this.props.intl.formatMessage({
                                    id: 'newPanel.operation.repeat',
                                    defaultMessage: '查重'
                                })}
                            </Button>}</Col></Row>}>
                            <Table
                                className="white-space-nowrap"
                                rowClassName={this.rowClassName}
                                rowKey="id"
                                columns={columns}
                                pagination={false}
                                dataSource={newdetails}
                                rowSelection={rowSelection}
                                scroll={{
                                    x: 'max-content',
                                    y: 430}}
                                size="small"
                                bordered={true} />
                        </Card>
                        {this.props.submitable && !this.state.isRepeat && (
                            <Card type="inner">
                                <Row>
                                    <Col className="col-align-right">
                                        <Button
                                            key="submit"
                                            loading={this.state.loading}
                                            onClick={this.onSubmit}
                                            type="primary">
                                            {this.props.intl.formatMessage({
                                                id: 'add.btn.submit',
                                                defaultMessage: '确认'
                                            })}
                                        </Button>
                                    </Col>
                                </Row>
                            </Card>
                        )}
                    </Form>
                </Spin>
                <div className="page-toolbar">
                    <Return
                        disabled={this.state.loading}
                        showWarning={this.state.hasOperat}
                        onConfirm={this.props.onCancel} />
                </div>
            </div>
        );
    }
}
Add.propTypes = {
    conditions: PropTypes.object.isRequired,
    init: PropTypes.func.isRequired,
    loading: PropTypes.bool.isRequired,
    submitable: PropTypes.bool.isRequired,
    onCancel: PropTypes.func.isRequired,
    onSubmit: PropTypes.func.isRequired,
    onUmount: PropTypes.func.isRequired,
    onUpdateDetail: PropTypes.func.isRequired,
    id: PropTypes.string,
    intl: PropTypes.object,
    isDealerUser: PropTypes.bool,
    isMoneyVisible: PropTypes.bool,
};
import {connect} from 'react-redux';
import {
    clearData,
    tableSearch,
    onClickUpdate,
    getEditInit,
    updateDetail,
    saveSubmitCondition,
} from './actions';
import {createSelector} from 'reselect';

import selectorFactory from 'Shared/utils/immutableToJsSelectorFactory';
const getSubmitData = selectorFactory(['page', 'appState', 'submitData']);
const getPermissions = createSelector(
    state => state.getIn(['page', 'domainData', 'permission', 'data']),
    state => state.getIn(['page', 'domainData', 'detail', 'data']),
    (permissions, detail) => {
        const {options = EMPTY_ARRAY} = detail.toJS();
        const data = permissions.toJS();
        return data.includes(PERMISSION.update) && options.includes(PERMISSION.update);
    }
);

const mapStateToProps = (state, ownProps) => ({
    id: ownProps.id,
    submitable: getPermissions(state, ownProps),
    loading: state.getIn(['page', 'domainData', 'detail', 'isFetching']) || state.getIn(['page', 'domainData', 'initData', 'isFetching']),
    conditions: getSubmitData(state),
    isDealerUser: state.getIn(['page', 'domainData', 'initData', 'isDealerUser']),
    isMoneyVisible: state.getIn((['page', 'domainData', 'initData', 'isMoneyVisible'])),
});

const mapDispatchToProps = (dispatch, ownProps) => ({
    init: () => dispatch(getEditInit(ownProps.id)),
    onSubmit: () =>
        dispatch(onClickUpdate(ownProps.id)).then(res => {
            if(res.ok) {
                dispatch(tableSearch({
                    pageIndex: PAGE.index
                }));
                ownProps.history.push(routes.query.url());
            }
            return res.ok;
        }),
    onCancel: () => {
        ownProps.history.push(routes.query.url());
    },
    onUmount: () => dispatch(clearData()),
    onUpdateDetail: newDetails => dispatch(updateDetail(newDetails)),
    onConditionsChange: (name, value) => dispatch(saveSubmitCondition(name, value)),
});

export default connect(
    mapStateToProps,
    mapDispatchToProps
)(injectIntl(Add));
